﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;

namespace Jemgine.Antioch
{
    public class Imgui
    {
       
        internal MouseState nextMouseState;
        internal MouseState previousMouseState;

        SpriteBatch Batch;
        ContentManager Content;
        Texture2D Border;
        SpriteFont Font;

        public Imgui(SpriteBatch Batch, ContentManager Content)
        {
            this.Batch = Batch;
            this.Content = Content;

            Border = Content.Load<Texture2D>("Engine.Content/border");
            Font = Content.Load<SpriteFont>("Antioch.Content/Hud");
        }

        public void BeginUI()
        {
            previousMouseState = nextMouseState;
            nextMouseState = Mouse.GetState();

            Batch.Begin();
        }

        public void EndUI()
        {
            Batch.End();
        }

        public enum ButtonEvent
        {
            MouseEnter,
            MouseUp,
            MouseLeave,
            None
        }

        public ButtonEvent Button(Rectangle rect, String label)
        {
            if (rect.Inside(nextMouseState.X, nextMouseState.Y))
            {
                Batch.BorderExplodeBlit(Border, rect.X, rect.Y, rect.Width, rect.Height, 2, 2, true, Color.Red);
                Batch.DrawString(Font, label, new Vector2(rect.X + 2, rect.Y + 2), Color.White);

                if (nextMouseState.LeftButton == ButtonState.Released && previousMouseState.LeftButton == ButtonState.Pressed)
                    return ButtonEvent.MouseUp;

                if (!rect.Inside(previousMouseState.X, previousMouseState.Y))
                    return ButtonEvent.MouseEnter;
            }
            else 
            {
                Batch.BorderExplodeBlit(Border, rect.X, rect.Y, rect.Width, rect.Height, 2, 2, true, Color.White);
                Batch.DrawString(Font, label, new Vector2(rect.X + 2, rect.Y + 2), Color.White);

                if (rect.Inside(previousMouseState.X, previousMouseState.Y))
                    return ButtonEvent.MouseLeave;
            }

            return ButtonEvent.None;
        }
    }

    public static class RectExtension
    {
        public static bool Inside(this Rectangle rect, int X, int Y)
        {
            return X >= rect.X && X < rect.X + rect.Width && Y >= rect.Y && Y < rect.Y + rect.Height;
        }
    }
}